<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          node-key="id"
          ref="deptTree"
          default-expand-all
          :expand-on-click-node="false"
          :data="depts"
          :props="defineProps"
          highlight-current
          @current-change="selectNode"
        >
        </el-tree>
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button
            size="mini"
            type="primary"
            @click="$router.push('/employee/detail')"
            >添加员工</el-button
          >
          <el-button size="mini" @click="showExcelDialog = true"
            >excel导入</el-button
          >
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30">
              </el-avatar>
              <span class="username" v-else>{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column width="280px" label="操作">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="mini"
                @click="$router.push(`/employee/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="mini" @click="btnRole(row.id)"
                >角色</el-button
              >
              <el-popconfirm
                title="确认删除该行数据吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button
                  slot="reference"
                  style="margin-left: 10px"
                  size="mini"
                  type="text"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changeSize"
          />
        </el-row>
      </div>
    </div>
    <!-- 放置导入组件 -->
    <ImportExcel
      :showExcelDialog.sync="showExcelDialog"
      @uploadSuccess="getEmployeeList"
    ></ImportExcel>
    <!-- 放置弹层组件 -->
    <el-dialog title="分配角色" :visible.sync="showRole">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{
          item.name
        }}</el-checkbox>
      </el-checkbox-group>
      <!-- 确认和取消按钮 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnRoleOK"
            >确定</el-button
          >
          <el-button size="mini" @click="showRole = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentInfo } from "@/api/department";
import { transListToTreeData } from "@/utils/index";
import {
  getEmployeeList,
  exportEmployee,
  delEmployee,
  getEnableRoleList,
  getEmployeeDetail,
  assignRole,
} from "@/api/employee";
import FileSaver from "file-saver";
import ImportExcel from "./components/import-excel.vue";

export default {
  name: "Employee",
  components: { ImportExcel },
  data() {
    return {
      currentIndexId: null, //记录当前的id
      roleIds: [], //绑定数据
      showRole: false, //控制角色的弹层的显示隐藏
      roleList: [], //放置弹出层的角色列表
      showExcelDialog: false, //控制弹层组件的隐藏
      total: 0,
      list: [],
      depts: [], //组织数据
      defineProps: {
        label: "name",
        children: "children",
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 8,
        keyword: "", // 模糊搜索字段
      },
    };
  },
  created() {
    this.getDepartmentInfo();
  },
  methods: {
    async getDepartmentInfo() {
      this.depts = transListToTreeData(await getDepartmentInfo(), 0);
      this.queryParams.departmentId = this.depts[0].id;
      // 设置选中节点
      // 树组件渲染是异步的  需要等到更新完毕之后
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId);
      });
      this.getEmployeeList();
    },
    // 点击其他部门的回调
    selectNode(node) {
      this.queryParams.page = 1;
      this.queryParams.departmentId = node.id;
      this.getEmployeeList();
    },
    // 获取员工列表的方法
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams);
      this.list = rows;
      this.total = total;
    },
    // 分页器换页的回调
    changeSize(newPage) {
      this.queryParams.page = newPage;
      this.getEmployeeList();
    },
    // 左上角全局搜索的回调
    changeValue() {
      // 单位时间内触发一次
      // 清除上一次的timer标记
      // this实例上赋值了一个timer属性（因为不是响应式数据无需放在data中声明）
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.queryParams.page = 1;
        this.getEmployeeList();
      }, 300);
    },
    // 员工excel导出的回调
    async exportEmployee() {
      const res = await exportEmployee();
      // FileSaver.saveAs（blob对象，文件名称.后缀）
      FileSaver.saveAs(res, "员工信息表.xlsx"); //下载文件
    },
    // 删除员工的回调
    async confirmDel(id) {
      await delEmployee(id);
      // 判断是否是当前页码的最后一个数据
      if (this.list.length === 1 && this.queryParams.page > 1)
        this.queryParams.page--;
      this.getEmployeeList();
      this.$message.success("删除页码成功");
    },
    // 操作角色按钮的回调
    async btnRole(id) {
      const res = await getEnableRoleList();
      this.roleList = res;
      this.currentIndexId = id;
      const { roleIds } = await getEmployeeDetail(id);
      this.roleIds = roleIds;
      this.showRole = true;
    },
    async btnRoleOK() {
      await assignRole({
        id: this.currentIndexId,
        roleIds: this.roleIds,
      });
      this.$message.success("分配用户角色成功");
      this.showRole = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
